﻿using System;
using System.Linq.Expressions;
using ECommerce.Web.HtmlHelpers;
using Selenium;

namespace ECommerce.IntegrationSpecs.TestHelpers
{
    public class Form<T>
    {
        private ISelenium selenium;

        public Form(ISelenium selenium)
        {
            this.selenium = selenium;
        }

        public Form<T> WithTextBox<TProperty>(Expression<Func<T, TProperty>> propertySelector, TProperty value)
        {
            string textBoxName = HtmlElementIdentityHelper.NameFor(propertySelector);

            this.selenium.Type(String.Format("name={0}", textBoxName), value.ToString());

            return this;
        }

        public void Submit()
        {
            string formId = GetFormId();

            string formLocator = String.Format("id={0}", formId);

            if (this.selenium.IsElementPresent(formLocator))
            {
                SubmitForm(formLocator);

                return;
            }

            SubmitForm("dom=document.forms[0]");
        }

        private string GetFormId()
        {
            return typeof(T).Name;
        }

        private void SubmitForm(string formLocator)
        {
            this.selenium.Submit(formLocator);

            this.selenium.WaitForPageToLoad("3000");
        }
    }
}
